//
//  SettingController.swift
//  eBooks
//
//  Created by JunMing on 2019/11/15.
//  Copyright © 2019 赵俊明. All rights reserved.
//

import UIKit
import RxCocoa
import RxSwift
import SSZipArchive

class SettingController: BaseController {
    fileprivate var tableView:UITableView!
    fileprivate lazy var bag:DisposeBag = DisposeBag()
    fileprivate var dataSource:[SetHeaderModel]?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "设置"
        setupTableView()
        let vModel = SetViewModel()
        vModel.modelObserable.asObservable().subscribe(onNext: { (data:[SetHeaderModel]) in
            self.dataSource = data
            self.tableView.reloadData()
        }).disposed(by: bag)
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "👈👈", style: .plain, target: self, action: #selector(backAciton))
    }
    
    func setupTableView() {
        tableView = UITableView(frame: view.bounds, style: .grouped)
        tableView.register(SettingCell.self, forCellReuseIdentifier: "cellid")
        tableView.delegate = self
        tableView.dataSource = self
        tableView.sectionHeaderHeight = 0;
        tableView.sectionFooterHeight = 0;
        tableView.backgroundColor = view.backgroundColor
        tableView.separatorColor = UIColor.RGBA(230, 230, 230, 0.8)
        view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.width.height.equalTo(view)
        }
    }
    
    @objc func backAciton() {
        self.dismiss(animated: true, completion: nil)
    }
}

extension SettingController:UITableViewDelegate,UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return dataSource!.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let header = dataSource![section]
        return header.items.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "cellid")
        if cell == nil {
            cell = SettingCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: "cellid")
        }
        let header = dataSource![indexPath.section]
        let cellNew = cell as! SettingCell
        cellNew.model = header.items[indexPath.row]
        return cellNew
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let header = dataSource![indexPath.section]
        let model = header.items[indexPath.row]
        if model.pushVC == "2" {
            showWIFIPage()
            MobClick.event("set_wifiChuanShu")
        }else if model.pushVC == "7" {
            showAlert("是否清空缓存", "120Kb缓存", true) { _ in
                print("清空缓存成功！")
            }
        }else if model.pushVC == "8" {
            MobClick.event("set_shareToFriends")
            shareImageToFriends(shareID: "123456", image: UIImage(named: "epub_icon")) { _, success in
                print("分享好友成功！")
            }
        }else if model.pushVC == "9" {
            let urlString = "https://itunes.apple.com/cn/app/ebook/id1501500754?mt=8"
            if let url = URL(string: urlString) {
                UIApplication.shared.open(url, options: [:], completionHandler: nil)
            }
        }else {
            if let vc = model.pushVC?.classFromString() {
                vc.title = model.title
                navigationController?.pushViewController(vc, animated: true)
            }
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 50
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 20
    }
    
    func classFromString(name: String) -> UIViewController? {
        if let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as! String? {
            let classStringName = appName + "." + name
            guard let newClass = NSClassFromString(classStringName) as? UIViewController.Type else {
                return nil
            }
            return (newClass.init() as! UIViewController)
        }
        return nil;
    }
    
    func showWIFIPage() {
        let manager = SGWiFiUploadManager.shared()
        let success = manager?.startHTTPServer(atPort: 10086)
        if success! {
            manager?.setFileUploadStartCallback({ (filename, sacepath) in })
            manager?.setFileUploadFinishCallback({ (fileName, savePath) in
                if let name = fileName,let fromPath = savePath {
                    if (fileName?.hasSuffix("zip"))! {
                        let newName = name.replacingOccurrences(of: "zip", with: "epub")
                        let toPath = Tools.documentPath()!+"/"+newName
                        SSZipArchive.unzipFile(atPath: fromPath, toDestination: toPath)
                        if let model = SQLHelper.share.fetchSigleModel(newName,true) {
                            model.isdel = false
                            SQLHelper.share.insertLocalDB(model)
                        }else {
                            let model = FileHelper.singleModel(newName)
                            model.isdel = false
                            SQLHelper.share.insertLocalDB(model)
                        }
                    }else if (fileName?.hasSuffix("epub"))! {
                        let toPath = Tools.documentPath()!+"/"+name
                        FileHelper.moveFile(fromPath, toPath)
                        if let model = SQLHelper.share.fetchSigleModel(name,true) {
                            model.isdel = false
                            SQLHelper.share.insertLocalDB(model)
                        }else {
                            let model = FileHelper.singleModel(name)
                            model.isdel = false
                            SQLHelper.share.insertLocalDB(model)
                        }
                    }
                }
            })
        }
        
        manager?.showWiFiPageFrontViewController(self, dismiss: {
            manager?.stopHTTPServer()
        })
    }
}

class SettingCell: UITableViewCell {
    var model:SetModel! {
        willSet {
            if let icon = newValue.icon {
                imaView.image = UIImage(named: icon)
            }
            title.text = newValue.title
        }
    }
    var title:UILabel!
    var imaView:UIImageView!
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        backgroundColor = UIColor.white
        selectionStyle = .none
        imaView = UIImageView(image: UIImage(named: "icons8-more"))
        imaView.contentMode = UIView.ContentMode.scaleAspectFill
        imaView.clipsToBounds = true;
        contentView.addSubview(imaView)
        
        title = UILabel()
        title.textColor = UIColor.black
        title.font = UIFont.regular(15)
        contentView.addSubview(title)
        layoutViews(true)
        
    }
    
    func layoutViews(_ iconShow:Bool) {
        imaView.snp.makeConstraints { (make) in
            make.width.height.equalTo(23)
            make.left.equalTo(contentView).offset(10)
            make.centerY.equalTo(contentView.snp_centerY)
        }
        title.snp.makeConstraints { (make) in
            make.height.equalTo(34)
            make.width.equalTo(120)
            make.left.equalTo(imaView.snp_right).offset(8)
            make.centerY.equalTo(imaView.snp_centerY)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
